package com.ayz.gateway.core.core.handlers;

import cn.hutool.log.Log;

import com.ayz.gateway.common.result.GatewayResult;
import com.ayz.gateway.common.result.ResponseCode;
import com.ayz.gateway.core.core.BaseHandler;
import com.ayz.gateway.core.core.HttpRequestParser;
import com.ayz.gateway.core.core.HttpResponseParser;
import com.ayz.gateway.core.core.common.AgreementConstants;
import com.ayz.gateway.core.core.common.CommandTypeConvert;
import com.ayz.gateway.core.core.common.UriParserUtils;
import com.ayz.gateway.core.session.http.HttpStatement;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.Map;

/**
 * @ClassName RequestParserHandler
 * @Description TODO: 请求参数解析Handler处理器
 * @Author 快乐的星球
 * @Date 2023/5/12 10:31
 * @Version 1.0
 **/
public class RequestParserHandler extends BaseHandler<FullHttpRequest> {
    private static final Log LOG=Log.get(RequestParserHandler.class);
    @Override
    public void openSession(ChannelHandlerContext channelHandlerContext, Channel channel, FullHttpRequest request) {
        LOG.info("网关接受到全局的Http请求;uri:{},method:{}",request.uri(),request.method());
        try {
            //1:获取HTTP资源路径
            String httpUri= UriParserUtils.getHttpUri(request.uri());
            //2:对HTTP请求参数进行解析
            Map<String, Object> parameters = HttpRequestParser.parseRequest(request);
            //3:准备好HttpStatement
            HttpStatement httpStatement=new HttpStatement(httpUri, CommandTypeConvert.convert(request.method()));
            httpStatement.setRequestPrams(parameters);

            //TODO: 将请求解析成功后的HttpStatement 放入Channel中
            //后序过程可以消费到
            channel.attr(AgreementConstants.HTTP_STATEMENT).set(httpStatement);
            //放行
            request.retain();
            channelHandlerContext.fireChannelRead(request);
        }catch (Exception ex){
            ex.printStackTrace();
            DefaultFullHttpResponse response=(DefaultFullHttpResponse) HttpResponseParser.parse(GatewayResult.error(ResponseCode.SERVER_HANDLE_FAILED,"服务器请求参数解析器处理失败"));
            channel.writeAndFlush(response);
        }
    }
}
